<!DOCTYPE html>
<html>
    <head>
		<meta charset="UTF-8">
		<title></title>
		
		<style type="text/css">
			canvas {
				display: block;
				border: 1px solid #AAAAAA;
				margin: 0 auto;
			}
            p {
                text-align: center;
            }
		</style>
		
	</head>
	<body>
		
		<!--<audio src="tgl.mp3" controls="controls" ></audio>-->
		
	    <!--<input type="file" id="music" />-->
		
		<canvas id="can" width="768" height="512"></canvas>
		<p id="info"></p>
		
	</body>
	
	
	<script>
		
		window.onload = function(){
			
			
			
			var mu = document.getElementById("music");
			var info = document.getElementById("info");
			
			
			StartAudio();
			function StartAudio(){
				var can = {
					w: 768,
					h: 512
				};
				
				
				var cxt = document.getElementById("can").getContext("2d");
				var line = cxt.createLinearGradient(0,0,0,can.h);
				line.addColorStop(0,"red");
				line.addColorStop(0.5,"yellow");
				line.addColorStop(1,"green");
				cxt.fillStyle = line;
				
				
	//			bufferSource  >>  analyser  >>  gainNode  >> ac.destination
				
				// 总
				var ac = new AudioContext();
				console.log(ac);
				
				// 控制音量
				var gainNode = ac.createGain();
				console.log(gainNode);
				gainNode.gain.value = 0.1;
				gainNode.connect(ac.destination);
				
				
				// 分析音频
				var analyser = ac.createAnalyser()
				analyser.fftSzie = 512;
				analyser.connect(gainNode);
				
				
				var xhr = new XMLHttpRequest();
				xhr.open("GET", "jljt.mp3", true);
				xhr.responseType = "arraybuffer";
				xhr.onload = function () {
                    info.innerText = "加载完毕";
				    ac.decodeAudioData(xhr.response, function (buffer) {
	//			        console.log(buffer);
				        
				        var bufferSource = ac.createBufferSource();
				        bufferSource.buffer = buffer;
				        
				        
				        bufferSource.connect(analyser);
	//			        bufferSource.connect(gainNode);
	//			        bufferSource.connect(ac.destination);
				        bufferSource.start();
				        
				        // 播放开始   分析数据
				        var arr = new Uint8Array(analyser.frequencyBinCount);
				        setInterval(function(){
					        analyser.getByteFrequencyData(arr);
	//			        	console.log(arr);
				        	canvas(arr);
				        },20);
				        
				    }, function(err){
				    	console.log(err);
				    });
				}
				xhr.send();
				info.innerText = "正在加载音乐，大约3.5M大小.....";
                
                
				function canvas(arr){
					cxt.clearRect(0, 0, can.w, can.h);
					var w = can.w / 32;
					for (var i = 0 ; i < 128 ; i++) {
						var h = arr[i] / 256 * can.h;
						cxt.fillRect(w*i, can.h - h, w*0.7, h)
					}
				}
			}
			
				
			
			
		}
		
		
	</script>
	
	
</html>